package com.itcast.demo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Test {

	public static void main(String[] args) throws IOException, TemplateException {
		//1. 创建一个配置对象
		Configuration configuration = new Configuration(Configuration.getVersion());
		//2. 设置模板所在的目录
		configuration.setDirectoryForTemplateLoading(new File("E:\\git\\gitee\\demo\\freemarker-demo\\src\\main\\resources"));
		//3. 设置字符集
		configuration.setDefaultEncoding("utf-8");
		//4. 获取模板对象
		Template template = configuration.getTemplate("test.ftl");
		//5. 创建数据模型(可以是对象,也可以是map)
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", "张三");
		map.put("message", "欢迎来到神奇的freemaker世界!");
		map.put("success", false);
		
		List<Map<String, Object>> fruitList = new ArrayList<Map<String,Object>>();
		Map<String, Object> fruit1 = new HashMap<String, Object>();
		fruit1.put("name", "apple");
		fruit1.put("price", 5.8);
		Map<String, Object> fruit2 = new HashMap<String, Object>();
		fruit2.put("name", "banana");
		fruit2.put("price", 2.5);
		Map<String, Object> fruit3 = new HashMap<String, Object>();
		fruit3.put("name", "orange");
		fruit3.put("price", 3.2);
		fruitList.add(fruit1);
		fruitList.add(fruit2);
		fruitList.add(fruit3);
		
		map.put("fruitList", fruitList);
		
		map.put("today", new Date());
		
		map.put("point", 1569687);
		
		//6. 创建一个输出流对象
		Writer out = new FileWriter("d:\\temp\\test.html");
		//7. 输出
		template.process(map, out);
		//8. 关闭输出流
		out.close();
	}
}
